package com.example.futureai.config.wbe.filter;

import cn.hutool.core.util.StrUtil;
import com.example.futureai.utils.TokenUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * @ClassName: JwtFilter
 * @Description:
 * @Author: YourName
 * @Date: 2025/2/27
 */
@WebFilter("/*")
public class JwtFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws ServletException, IOException {
        // 获取请求的 URL
        StringBuffer requestURL = request.getRequestURL();
        // 如果请求路径是 /login，直接放行
        if (requestURL.toString().contains("/chatLogin")) {
            chain.doFilter(request, response);
            return;
        }

        if(requestURL.toString().matches(".+.ico$")){
            chain.doFilter(request, response);
            return;
        }
        // 获取 Authorization 请求头
        String token = request.getHeader("Authorization");
        if(StrUtil.isBlank(token)){
            //从参数中获取token
            token = request.getParameter("token");
        }
        // 如果请求头中不包含 Authorization 字段，返回 401 Unauthorized
        if (StrUtil.isBlank(token)) {
            sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "未提供 Token，请重新登录");
            return;
        }

//        // 验证 Token 是否有效
        if (!TokenUtil.validToken(token)) {
            sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "Token 无效或已过期，请重新登录");
            return;
        }


        // 如果 Token 有效，继续处理请求
        chain.doFilter(request, response);
    }

    /**
     * 发送错误响应
     *
     * @param response    HttpServletResponse 对象
     * @param statusCode  状态码
     * @param message     错误信息
     */
    private void sendErrorResponse(HttpServletResponse response, int statusCode, String message) throws IOException {
        response.setStatus(statusCode); // 设置状态码
        response.setContentType("application/json"); // 设置响应内容类型为 JSON
        response.setCharacterEncoding("UTF-8"); // 设置字符编码
        // 构造 JSON 响应
        String jsonResponse = String.format("{\"code\": %d, \"msg\": \"%s\"}", statusCode, message);
        response.getWriter().write(jsonResponse); // 写入响应
    }
}
